use std::net::SocketAddr;
use axum::extract::{ConnectInfo, State};
use axum::http::HeaderMap;
use axum::{Json, Router};
use axum::response::IntoResponse;
use axum::routing::post;
use serde::{Deserialize, Serialize};
use void_log::log_info;
use crate::model::sys_guild::SysGuild;
use crate::satori_api::SatoriList;
use crate::http_api;
use crate::ws::AppState;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SatoriGuildData {
    pub guild_id: Option<String>,    //群组 ID
    pub next: Option<String>,    //分页令牌
    pub message_id: Option<String>,    //请求 ID
    pub approve: Option<bool>,    //是否通过请求
    pub comment: Option<String>,    //备注信息
}

async fn guild_list(State(app_state): State<AppState>,
                        headers: HeaderMap, ConnectInfo(addr): ConnectInfo<SocketAddr>,
                        Json(guild_data): Json<SatoriGuildData>) -> impl IntoResponse {
    log_info!("Connection address {}", &addr.to_string());
    // 获取user_token
    let list = if let Some(user_token) = http_api::get_user_token(headers) {
        let next = guild_data.next.unwrap_or_default();
        // 根据用户token查询群列表
        let sys_guilds = SysGuild::select_user_token(&app_state.pool.clone(), &user_token).await.unwrap();
        // 组装返回
        SatoriList::new(sys_guilds, &next)
    } else { Default::default() };
    Json(list)
}

pub async fn router(app: Router<AppState>) -> Router<AppState> {
    app.route("/guild.list", post(guild_list))
}